package org.fall.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.fall.srb.core.listener.ExcelDictDtoListener;
import org.fall.srb.core.pojo.dto.ExcelDictDTO;
import org.fall.srb.core.pojo.entity.Dict;
import org.fall.srb.core.mapper.DictMapper;
import org.fall.srb.core.service.DictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author sprogFall
 * @since 2021-06-23
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private DictMapper dictMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDtoListener(dictMapper)).sheet().doRead();
        log.info("Excel数据导入成功");
    }

    @Override
    public List<ExcelDictDTO> exportData() {
        List<Dict> dictList = dictMapper.selectList(null);
        List<ExcelDictDTO> result = new ArrayList<>();
        dictList.forEach(dict -> {
            ExcelDictDTO excelDictDTO = new ExcelDictDTO();
            BeanUtils.copyProperties(dict, excelDictDTO);
            result.add(excelDictDTO);
        });
        return result;
    }

    @Override
    public List<Dict> getDictByParentId(Long parentId) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        List<Dict> dictList = dictMapper.selectList(queryWrapper);
        dictList.forEach(dict -> {
            dict.setHasChildren(hasChildren(dict.getId()));
        });
        return dictList;
    }

    private Boolean hasChildren(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        Integer childrenCount = dictMapper.selectCount(queryWrapper);
        return childrenCount > 0;
    }
}
